use std::sync::{Arc, Mutex};
use std::thread;
use flume::{Sender, Receiver, bounded};
use crate::context::Context;
use crate::message::Message;
use crate::actors::Actor;
use crate::mailbox::MailboxSender;

// 定义 BoundedMailbox
pub struct BoundedMailbox {
    sender: Sender<Box<dyn Message>>,
}

impl BoundedMailbox {
    pub fn new(actor: Arc<Mutex<dyn Actor + Send>>, size: usize) -> Self {
        let (sender, receiver) = bounded(size);
        let actor_clone = actor.clone();
        thread::spawn(move || {
            let context = Context::new(receiver);
            loop {
                if let Ok(msg) = context.receiver.recv() {
                    let mut actor = actor_clone.lock().unwrap();
                    actor.receive(&context, msg);
                }
            }
        });

        BoundedMailbox { sender }
    }
}

impl MailboxSender for BoundedMailbox {
    fn send(&self, msg: Box<dyn Message>) {
        self.sender.send(msg).unwrap();
    }
}